import 'dart:ui' show Color;

import 'package:flutter/material.dart';
import 'package:uuid/uuid.dart';
import 'package:uuid/uuid_util.dart';

import '../model/health_record.dart';
import '../service/database_service.dart';
import '../service/theme_notifier.dart';
import '../service/theme_service.dart';
import '../state/record_states.dart';
import '../theme/neumorphic_theme.dart';

Color getRecordTypeColor(RecordType type) {
  switch (type) {
    case RecordType.feeding:
      return Colors.blue;
    case RecordType.diaper:
      return Colors.green;
    case RecordType.sleep:
      return Colors.purple;
    case RecordType.temperature:
      return Colors.orange;
    case RecordType.medicine:
      return Colors.red;
    default:
      return Colors.grey;
  }
}

String getRecordTypeText(RecordType type) {
  switch (type) {
    case RecordType.feeding:
      return '喂奶';
    case RecordType.diaper:
      return '换尿布';
    case RecordType.sleep:
      return '睡眠';
    case RecordType.temperature:
      return '体温';
    case RecordType.medicine:
      return '用药';
    case RecordType.vaccine:
      return '疫苗';
    case RecordType.weight:
      return '体重';
    case RecordType.height:
      return '身高';
    case RecordType.custom:
      return '自定义';
    case RecordType.doctor:
      return '就医';
    case RecordType.milestone:
      return '里程碑';
    case RecordType.food:
      return '辅食';
    case RecordType.activity:
      return '活动';
    case RecordType.mood:
      return '心情';
  }
}

Icon getRecordTypeIcon(RecordType type) {
  switch (type) {
    case RecordType.feeding:
      return const Icon(Icons.local_cafe); // 奶瓶图标
    case RecordType.diaper:
      return const Icon(Icons.cleaning_services); // 尿布图标
    case RecordType.sleep:
      return const Icon(Icons.nightlight_round); // 月亮图标
    case RecordType.temperature:
      return const Icon(Icons.thermostat); // 温度计图标
    case RecordType.medicine:
      return const Icon(Icons.medication); // 药品图标
    case RecordType.vaccine:
      return const Icon(Icons.vaccines); // 疫苗图标
    case RecordType.weight:
      return const Icon(Icons.monitor_weight); // 体重秤图标
    case RecordType.height:
      return const Icon(Icons.height); // 身高图标
    case RecordType.custom:
      return const Icon(Icons.note_add); // 自定义记录图标
    case RecordType.doctor:
      return const Icon(Icons.local_hospital); // 就医图标
    case RecordType.milestone:
      return const Icon(Icons.emoji_events); // 里程碑图标
    case RecordType.food:
      return const Icon(Icons.restaurant); // 辅食图标
    case RecordType.activity:
      return const Icon(Icons.directions_run); // 活动图标
    case RecordType.mood:
      return const Icon(Icons.mood); // 心情图标
    default:
      return const Icon(Icons.event_note); // 默认图标
  }
}

class DialogState {
  final textController = TextEditingController();
  final dataNotifier = ValueNotifier<Map<String, dynamic>>({});
  bool isDisposed = false;

  void dispose() {
    if (!isDisposed) {
      textController.dispose();
      dataNotifier.dispose();
      isDisposed = true;
    }
  }
}

void showRecordDialogByType(
  BuildContext context,
  RecordType type,
  String babyId,
) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  final themeColors =
      ThemeService.themeColors[ThemeNotifier.instance.currentTheme]!;

  // Create specific state based on record type
  final recordState = switch (type) {
    RecordType.feeding => FeedingState(),
    RecordType.diaper => DiaperState(),
    RecordType.temperature => TemperatureState(),
    RecordType.medicine => MedicineState(),
    RecordType.weight => WeightState(),
    RecordType.height => HeightState(),
    RecordType.sleep => SleepState(),
    RecordType.food => FoodState(),
    RecordType.milestone => MilestoneState(),
    RecordType.doctor => DoctorState(),
    RecordType.vaccine => VaccineState(),
    RecordType.custom => CustomState(),
    _ => CustomState(),
  };

  Future<void> saveRecord() async {
    try {
      if (!recordState.isValid) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请输入记录内容'), backgroundColor: Colors.red),
        );
        return;
      }

      final record = HealthRecord(
        id: const Uuid().v4(),
        babyId: babyId,
        type: type,
        timestamp: DateTime.now(),
        data: recordState.data,
      );

      await DatabaseService().addHealthRecord(record);

      if (!recordState.isDisposed) {
        Navigator.pop(context);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('记录已保存'),
            backgroundColor: themeColors.primary,
          ),
        );
      }
    } catch (e) {
      if (!recordState.isDisposed) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('保存失败'), backgroundColor: Colors.red),
        );
      }
    }
  }

  // Show dialog with specific state
  showDialog(
    context: context,
    builder:
        (context) => Dialog(
          backgroundColor: Colors.transparent,
          child: PopScope(
            onPopInvoked: (_) {
              recordState.dispose();
            },
            child: SingleChildScrollView(
              child: Container(
                child: Column(
                  children: [
                    // ... existing title section ...

                    // Input Section
                    _buildInputSection(context, type, recordState),

                    // Notes TextField
                    Container(
                      decoration: NeumorphicTheme.insetDecoration(
                        baseColor: backgroundColor,
                        borderRadius: BorderRadius.circular(16),
                      ),
                      child: TextField(
                        controller: recordState.noteController,
                        decoration: InputDecoration(
                          hintText: '添加备注',
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(16),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: const EdgeInsets.all(12),
                        ),
                        maxLines: 2,
                      ),
                    ),

                    // Action Buttons
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        _buildNeumorphicButton(
                          context,
                          '取消',
                          onTap: () {
                            recordState.dispose();
                            Navigator.pop(context);
                          },
                          isPrimary: false,
                        ),
                        _buildNeumorphicButton(
                          context,
                          '保存',
                          onTap: saveRecord,
                          isPrimary: true,
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
  );
}

Widget _buildNeumorphicButton(
  BuildContext context,
  String text, {
  required VoidCallback onTap,
  bool isPrimary = false,
}) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  final themeColors =
      ThemeService.themeColors[ThemeNotifier.instance.currentTheme]!;

  return GestureDetector(
    onTap: onTap,
    child: Container(
      padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 12),
      decoration: NeumorphicTheme.surfaceDecoration(
        baseColor: backgroundColor,
        borderRadius: BorderRadius.circular(24),
      ),
      child: Text(
        text,
        style: TextStyle(
          color: isPrimary ? themeColors.primary : Colors.grey[600],
          fontWeight: FontWeight.bold,
        ),
      ),
    ),
  );
}

Widget _buildInputSection(
  BuildContext context,
  RecordType type,
  BaseRecordState recordState,
) {
  switch (type) {
    case RecordType.feeding:
      return _buildFeedingInput(context, recordState as FeedingState);
    case RecordType.temperature:
      return _buildTemperatureInput(context, recordState as TemperatureState);
    case RecordType.medicine:
      return _buildMedicineInput(context, recordState as MedicineState);
    case RecordType.weight:
      return _buildWeightInput(context, recordState as WeightState);
    case RecordType.height:
      return _buildHeightInput(context, recordState as HeightState);
    case RecordType.sleep:
      return _buildSleepInput(context, recordState as SleepState);
    case RecordType.food:
      return _buildFoodInput(context, recordState as FoodState);
    case RecordType.milestone:
      return _buildMilestoneInput(context, recordState as MilestoneState);
    case RecordType.doctor:
      return _buildDoctorInput(context, recordState as DoctorState);
    case RecordType.vaccine:
      return _buildVaccineInput(context, recordState as VaccineState);
    case RecordType.diaper:
      return _buildDiaperInput(context, recordState as DiaperState);
    case RecordType.custom:
      return _buildCustomInput(context, recordState as CustomState);
    default:
      return const SizedBox.shrink();
  }
}

// Update one of the input builders as an example:
Widget _buildFeedingInput(BuildContext context, FeedingState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.amountController,
          decoration: InputDecoration(
            hintText: '喂奶量(ml)',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
          keyboardType: TextInputType.number,
        ),
      ),
    ],
  );
}

Widget _buildTemperatureInput(BuildContext context, TemperatureState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

  return Container(
    decoration: NeumorphicTheme.insetDecoration(
      baseColor: backgroundColor,
      borderRadius: BorderRadius.circular(12),
    ),
    child: TextField(
      controller: state.tempController,
      decoration: InputDecoration(
        hintText: '体温(°C)',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.all(16),
      ),
      keyboardType: TextInputType.numberWithOptions(decimal: true),
    ),
  );
}

Widget _buildMedicineInput(BuildContext context, MedicineState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;

  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.nameController,
          decoration: InputDecoration(
            hintText: '药品名称',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
      const SizedBox(height: 12),
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.doseController,
          decoration: InputDecoration(
            hintText: '剂量',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
    ],
  );
}

Widget _buildWeightInput(BuildContext context, WeightState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Container(
    decoration: NeumorphicTheme.insetDecoration(
      baseColor: backgroundColor,
      borderRadius: BorderRadius.circular(12),
    ),
    child: TextField(
      controller: state.weightController,
      decoration: InputDecoration(
        hintText: '体重(kg)',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.all(16),
      ),
      keyboardType: TextInputType.numberWithOptions(decimal: true),
    ),
  );
}

Widget _buildHeightInput(BuildContext context, HeightState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Container(
    decoration: NeumorphicTheme.insetDecoration(
      baseColor: backgroundColor,
      borderRadius: BorderRadius.circular(12),
    ),
    child: TextField(
      controller: state.heightController,
      decoration: InputDecoration(
        hintText: '身高(cm)',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.all(16),
      ),
      keyboardType: TextInputType.numberWithOptions(decimal: true),
    ),
  );
}

Widget _buildSleepInput(BuildContext context, SleepState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  final themeColors =
      ThemeService.themeColors[ThemeNotifier.instance.currentTheme]!;

  Future<void> selectTime(bool isStartTime) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
      builder: (BuildContext context, Widget? child) {
        return Theme(
          data: Theme.of(context).copyWith(
            colorScheme: ColorScheme.light(primary: themeColors.primary),
          ),
          child: child!,
        );
      },
    );

    if (picked != null) {
      final now = DateTime.now();
      final selectedTime = DateTime(
        now.year,
        now.month,
        now.day,
        picked.hour,
        picked.minute,
      );

      if (isStartTime) {
        state.startTime = selectedTime;
      } else {
        state.endTime = selectedTime;
      }
    }
  }

  String _formatTime(DateTime? time) {
    if (time == null) return '';
    return '${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}';
  }

  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: ListTile(
          onTap: () => selectTime(true),
          title: Text(
            state.startTime != null ? _formatTime(state.startTime) : '选择开始时间',
            style: TextStyle(
              color: state.startTime != null ? Colors.black87 : Colors.grey,
            ),
          ),
          trailing: Icon(Icons.access_time, color: themeColors.primary),
        ),
      ),
      const SizedBox(height: 12),
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: ListTile(
          onTap: () => selectTime(false),
          title: Text(
            state.endTime != null ? _formatTime(state.endTime) : '选择结束时间',
            style: TextStyle(
              color: state.endTime != null ? Colors.black87 : Colors.grey,
            ),
          ),
          trailing: Icon(Icons.access_time, color: themeColors.primary),
        ),
      ),
    ],
  );
}

Widget _buildFoodInput(BuildContext context, FoodState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.nameController,
          decoration: InputDecoration(
            hintText: '食物名称',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
      const SizedBox(height: 12),
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.amountController,
          decoration: InputDecoration(
            hintText: '用量',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
    ],
  );
}

Widget _buildMilestoneInput(BuildContext context, MilestoneState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Container(
    decoration: NeumorphicTheme.insetDecoration(
      baseColor: backgroundColor,
      borderRadius: BorderRadius.circular(12),
    ),
    child: TextField(
      controller: state.eventController,
      decoration: InputDecoration(
        hintText: '里程碑事件',
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(12),
          borderSide: BorderSide.none,
        ),
        contentPadding: const EdgeInsets.all(16),
      ),
      maxLines: 2,
    ),
  );
}

Widget _buildDoctorInput(BuildContext context, DoctorState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.hospitalController,
          decoration: InputDecoration(
            hintText: '医院名称',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
      const SizedBox(height: 12),
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.reasonController,
          decoration: InputDecoration(
            hintText: '就诊原因',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
          maxLines: 2,
        ),
      ),
    ],
  );
}

Widget _buildVaccineInput(BuildContext context, VaccineState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.nameController,
          decoration: InputDecoration(
            hintText: '疫苗名称',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
      const SizedBox(height: 12),
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.locationController,
          decoration: InputDecoration(
            hintText: '接种地点',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
    ],
  );
}

Widget _buildDiaperInput(BuildContext context, DiaperState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  String selectedType = state.selectedType;

  return Container(
    padding: const EdgeInsets.all(16),
    decoration: NeumorphicTheme.insetDecoration(
      baseColor: backgroundColor,
      borderRadius: BorderRadius.circular(16),
    ),
    child: StatefulBuilder(
      builder: (context, setState) {
        return Wrap(
          spacing: 12,
          runSpacing: 12,
          alignment: WrapAlignment.center,
          children: [
            _buildDiaperTypeButton(
              context,
              '尿尿',
              Icons.water_drop_outlined,
              'wet',
              selectedType,
              (value) {
                setState(() => selectedType = value);
                state.selectedType = value;
              },
            ),
            _buildDiaperTypeButton(
              context,
              '便便',
              Icons.bathroom_outlined,
              'dirty',
              selectedType,
              (value) {
                setState(() => selectedType = value);
                state.selectedType = value;
              },
            ),
            _buildDiaperTypeButton(
              context,
              '都有',
              Icons.check_circle_outline,
              'both',
              selectedType,
              (value) {
                setState(() => selectedType = value);
                state.selectedType = value;
              },
            ),
          ],
        );
      },
    ),
  );
}

Widget _buildDiaperTypeButton(
  BuildContext context,
  String label,
  IconData icon,
  String value,
  String? selectedValue,
  ValueChanged<String> onChanged,
) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  final themeColors =
      ThemeService.themeColors[ThemeNotifier.instance.currentTheme]!;
  final isSelected = selectedValue == value;

  return GestureDetector(
    onTap: () => onChanged(value),
    child: Container(
      width: 72,
      padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 4),
      decoration: NeumorphicTheme.surfaceDecoration(
        baseColor: backgroundColor,
        borderRadius: BorderRadius.circular(12),
        isPressed: isSelected,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            icon,
            color: isSelected ? themeColors.primary : Colors.grey,
            size: 24,
          ),
          const SizedBox(height: 6),
          Text(
            label,
            style: TextStyle(
              color: isSelected ? themeColors.primary : Colors.grey,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              fontSize: 13,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    ),
  );
}

Widget _buildCustomInput(BuildContext context, CustomState state) {
  final backgroundColor = Theme.of(context).scaffoldBackgroundColor;
  return Column(
    children: [
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.titleController,
          decoration: InputDecoration(
            hintText: '事件标题',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
        ),
      ),
      const SizedBox(height: 12),
      Container(
        decoration: NeumorphicTheme.insetDecoration(
          baseColor: backgroundColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: TextField(
          controller: state.contentController,
          decoration: InputDecoration(
            hintText: '事件内容',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.circular(12),
              borderSide: BorderSide.none,
            ),
            contentPadding: const EdgeInsets.all(16),
          ),
          maxLines: 3,
        ),
      ),
    ],
  );
}
